import { ref } from 'vue'
import { Toast } from 'vant'
import api from '@/api'

export default function useVerify() {
  const countDown = ref(-1)

  const onSendVerifyCode = async mobile => {
    if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(mobile)) {
      Toast('请填写正确的手机号码')
      return
    }
    if (countDown.value >= 0) {
      return
    }

    countDown.value = 120
    const timer = setInterval(() => {
      countDown.value--
      if (countDown.value === 0) {
        clearInterval(timer)
        countDown.value = -1
      }
    }, 1000)

    const res = await api.getSmsCode({
      mobile: btoa(mobile)
    })

    if (res.error) {
      Toast(res.error.message)
      countDown.value = 0
      return
    }

    Toast(res.data.message)
  }

  return {
    countDown,
    onSendVerifyCode
  }
}
